package cards.controller;

import cards.dao.AttendedCardActivityDao;
import cards.dao.CardActivityDao;
import cards.entity.AttendedCardActivity;
import cards.entity.CardActivity;
import cards.entity.User;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import cards.service.AttendedCardActivityService;
import cards.service.CardActivityService;
import cards.util.HostHolder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
public class DetailController {
    @Value("${path.upload}")
    private String uploadPath;
    @Value("${path.domain}")
    private String domain;
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private CardActivityService cardActivityService;

    @Autowired
    private AttendedCardActivityService attendedCardActivityService;
    @Autowired
    private AttendedCardActivityDao attendedCardActivityDao;
    @Autowired
    private CardActivityDao cardActivityDao;
    @Autowired
    private HostHolder hostHolder;

    @RequestMapping(path = "/detail/{id}", method = RequestMethod.GET)
    public String displayDetailByUserAndActivity(@PathVariable String id, Model model) {
        User user = hostHolder.getUser();

        AttendedCardActivity myActivity = attendedCardActivityService.findAttendedCardActivityById(Long.valueOf(id));
        String title = myActivity.getTitle();
        CardActivity activity = cardActivityService.findCardActivityByExactTitle(title);

        List<String> imglist = new ArrayList<>();

        byte[] fileByte0 = null;
        byte[] fileByte1 = null;
        byte[] fileByte2 = null;
        byte[] fileByte3 = null;
        byte[] fileByte4 = null;
        byte[] fileByte5 = null;

        String img0 = null;
        String img1 = null;
        String img2 = null;
        String img3 = null;
        String img4 = null;
        String img5 = null;

        try {
            String path0 = uploadPath + "\\" + activity.getPublicityPicture();
            String path1 = uploadPath + "\\" + activity.getCardPicture1();
            String path2 = uploadPath + "\\" + activity.getCardPicture2();
            String path3 = uploadPath + "\\" + activity.getCardPicture3();
            String path4 = uploadPath + "\\" + activity.getCardPicture4();
            String path5 = uploadPath + "\\" + activity.getCardPicture5();

            File file0 = new File(path0);
            fileByte0 = Files.readAllBytes(file0.toPath());
            File file1 = new File(path1);
            fileByte1 = Files.readAllBytes(file1.toPath());
            File file2 = new File(path2);
            fileByte2 = Files.readAllBytes(file2.toPath());
            File file3 = new File(path3);
            fileByte3 = Files.readAllBytes(file3.toPath());
            File file4 = new File(path4);
            fileByte4 = Files.readAllBytes(file4.toPath());
            File file5 = new File(path5);
            fileByte5 = Files.readAllBytes(file5.toPath());

            img0 = Base64.encodeBase64String(fileByte0);
            img1 = Base64.encodeBase64String(fileByte1);
            img2 = Base64.encodeBase64String(fileByte2);
            img3 = Base64.encodeBase64String(fileByte3);
            img4 = Base64.encodeBase64String(fileByte4);
            img5 = Base64.encodeBase64String(fileByte5);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(myActivity.getCard1() == null){imglist.add(null);}else {imglist.add(img1);}
        if(myActivity.getCard2() == null){imglist.add(null);}else {imglist.add(img2);}
        if(myActivity.getCard3() == null){imglist.add(null);}else {imglist.add(img3);}
        if(myActivity.getCard4() == null){imglist.add(null);}else {imglist.add(img4);}
        if(myActivity.getCard5() == null){imglist.add(null);}else {imglist.add(img5);}

        model.addAttribute("cardActivity", activity);
        model.addAttribute("user", user);
        model.addAttribute("myCardActivity", myActivity);
        model.addAttribute("imglist", imglist);
        model.addAttribute("publicityImage", img0);

        return "detail";
    }

    @RequestMapping(path="/scratch/{id}",method=RequestMethod.GET)
    public String scratch(@PathVariable String id, Model model)
    {
        User user = hostHolder.getUser();
        model.addAttribute("user", user);
        AttendedCardActivity myActivity = attendedCardActivityService.findAttendedCardActivityById(Long.valueOf(id));
        String title = myActivity.getTitle();
        CardActivity activity = cardActivityService.findCardActivityByExactTitle(title);
        Long availableScratchTimes = myActivity.getAvailableScratchTimes();
        if(availableScratchTimes > 0) {
            attendedCardActivityDao.updateAvailableScratchTimes(Long.valueOf(id),availableScratchTimes - 1);
            Random r = new Random();
            double rand = r.nextDouble();
            float r1 = activity.getCardProbability1();
            float r2 = activity.getCardProbability2() + r1;
            float r3 = activity.getCardProbability3() + r2;
            float r4 = activity.getCardProbability4() + r3;

            if (rand < r1) {attendedCardActivityDao.updateCard1ById(Long.valueOf(id), new Date());
                model.addAttribute("result", "恭喜你，刮出第一张卡片！");myActivity.setCard1(new Date());}
            else if (rand < r2) {attendedCardActivityDao.updateCard2ById(Long.valueOf(id), new Date());
                model.addAttribute("result", "恭喜你，刮出第二张卡片！");myActivity.setCard2(new Date());}
            else if (rand < r3) {attendedCardActivityDao.updateCard3ById(Long.valueOf(id), new Date());
                model.addAttribute("result", "恭喜你，刮出第三张卡片！");myActivity.setCard3(new Date());}
            else if (rand < r4) {attendedCardActivityDao.updateCard4ById(Long.valueOf(id), new Date());
                model.addAttribute("result", "恭喜你，刮出第四张卡片！");myActivity.setCard4(new Date());}
            else {attendedCardActivityDao.updateCard5ById(Long.valueOf(id), new Date());
                model.addAttribute("result", "恭喜你，刮出第五张卡片！");myActivity.setCard5(new Date());}
        }else model.addAttribute("result", "刮卡次数不足，邀请朋友可以获得刮卡次数！");

        List<String> imglist = new ArrayList<>();

        byte[] fileByte0 = null;
        byte[] fileByte1 = null;
        byte[] fileByte2 = null;
        byte[] fileByte3 = null;
        byte[] fileByte4 = null;
        byte[] fileByte5 = null;

        String img0 = null;
        String img1 = null;
        String img2 = null;
        String img3 = null;
        String img4 = null;
        String img5 = null;

        try {
            String path0 = uploadPath + "\\" + activity.getPublicityPicture();
            String path1 = uploadPath + "\\" + activity.getCardPicture1();
            String path2 = uploadPath + "\\" + activity.getCardPicture2();
            String path3 = uploadPath + "\\" + activity.getCardPicture3();
            String path4 = uploadPath + "\\" + activity.getCardPicture4();
            String path5 = uploadPath + "\\" + activity.getCardPicture5();

            File file0 = new File(path0);
            fileByte0 = Files.readAllBytes(file0.toPath());
            File file1 = new File(path1);
            fileByte1 = Files.readAllBytes(file1.toPath());
            File file2 = new File(path2);
            fileByte2 = Files.readAllBytes(file2.toPath());
            File file3 = new File(path3);
            fileByte3 = Files.readAllBytes(file3.toPath());
            File file4 = new File(path4);
            fileByte4 = Files.readAllBytes(file4.toPath());
            File file5 = new File(path5);
            fileByte5 = Files.readAllBytes(file5.toPath());

            img0 = Base64.encodeBase64String(fileByte0);
            img1 = Base64.encodeBase64String(fileByte1);
            img2 = Base64.encodeBase64String(fileByte2);
            img3 = Base64.encodeBase64String(fileByte3);
            img4 = Base64.encodeBase64String(fileByte4);
            img5 = Base64.encodeBase64String(fileByte5);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 判断这张卡是不是被刮出来了
        if(myActivity.getCard1() == null){imglist.add(null);}else {imglist.add(img1);}
        if(myActivity.getCard2() == null){imglist.add(null);}else {imglist.add(img2);}
        if(myActivity.getCard3() == null){imglist.add(null);}else {imglist.add(img3);}
        if(myActivity.getCard4() == null){imglist.add(null);}else {imglist.add(img4);}
        if(myActivity.getCard5() == null){imglist.add(null);}else {imglist.add(img5);}

        // 更新活动信息
        cardActivityDao.updateParticipants(activity.getId(), activity.getParticipants() + 1);
        if(myActivity.getCard1() != null && myActivity.getCard2() != null && myActivity.getCard3() != null  && myActivity.getCard4() != null && myActivity.getCard5() != null )
            cardActivityDao.updateFullCollectors(activity.getId(), activity.getFullCollectors() + 1);

        model.addAttribute( "cardActivity", activity);
        model.addAttribute("user", user);
        model.addAttribute("myCardActivity", myActivity);
        model.addAttribute("imglist", imglist);
        model.addAttribute("publicityImage", img0);
        return "detail";
    }
}
